package com.ptmall.app.ui.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.ptmall.app.R;
import com.ptmall.app.alipay.AliPay;
import com.ptmall.app.base.BaseMvpActivity;
import com.ptmall.app.base.PermissionListener;
import com.ptmall.app.bean.PayBean;
import com.ptmall.app.bean.model.db.Account;
import com.ptmall.app.net.api.ApiDataRepository;
import com.ptmall.app.net.base.ApiNetResponse;
import com.ptmall.app.view.OilPassDialog;
import com.ptmall.app.view.TitleBarView;
import com.xfly.app.wxapi.PayResultListener;
import com.xfly.app.wxapi.WxPay;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PayActivity extends BaseMvpActivity {

    TitleBarView titlebar;

    CheckBox ali_check, wx_check, keyong_check;
    TextView walletnum, keyong;

    ApiDataRepository apiDataRepository = ApiDataRepository.getInstance();

    String aid;
    String cardid;
    String price;
    String desc;
    String couponId;
    String pei_date;
    String pei_time;

    String orderId = "";

    Button enter;

    private String[] PAY_PERMISSION = {
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};

    OilPassDialog oilPassDialog;
    Account account;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setView(R.layout.activity_pay);
    }

    @Override
    public void initViews() {
        titlebar = (TitleBarView) findViewById(R.id.titlebar);
        ali_check = (CheckBox) findViewById(R.id.ali_check);
        wx_check = (CheckBox) findViewById(R.id.wx_check);
        walletnum = (TextView) findViewById(R.id.walletnum);
        keyong = (TextView) findViewById(R.id.keyong);
        keyong_check = (CheckBox) findViewById(R.id.keyong_check);
        enter = (Button) findViewById(R.id.enter);
    }

    @Override
    public void initEvents() {
        if (getIntent().getStringExtra("orderId") == null) {

            aid = getIntent().getStringExtra("addressid");
            cardid = getIntent().getStringExtra("cartIds");
            price = getIntent().getStringExtra("orders_total");
            desc = getIntent().getStringExtra("desc");
            couponId = getIntent().getStringExtra("couponid");
            pei_time = getIntent().getStringExtra("pei_time");
            pei_date = getIntent().getStringExtra("pei_date");
        } else {
            orderId = getIntent().getStringExtra("orderId");
            price = getIntent().getStringExtra("orders_total");
        }
        ali_check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    wx_check.setChecked(false);
                    keyong_check.setChecked(false);
                }
            }
        });
        wx_check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    ali_check.setChecked(false);
                    keyong_check.setChecked(false);
                }
            }
        });
        keyong_check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if(account!=null&&new BigDecimal(account.wallet).doubleValue()<new BigDecimal(price).doubleValue()){
                    showMsg("可用余额不足");
                    keyong_check.setChecked(false);
                }
                if (b) {
                    ali_check.setChecked(false);
                    wx_check.setChecked(false);
                }
            }
        });

        titlebar.setOnTitleBarClickListener(new TitleBarView.TitleBarClickListener() {
            @Override
            public void leftClick() {
                finish();
            }

            @Override
            public void rightClick() {

            }
        });
        enter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                getUserInfo();
            }
        });

        walletnum.setText("￥" + price);
    }

    @Override
    protected void onResume() {
        super.onResume();
        getWalletNum();
    }

    private void getWalletNum() {
        apiDataRepository.getUserInfo(null, new ApiNetResponse<Account>() {
            @Override
            public void onSuccess(Account data) {
                account = data;
                keyong.setText("可用余额￥" + data.wallet);
            }
        });
    }

    private void getUserInfo() {
        apiDataRepository.getUserInfo(null, new ApiNetResponse<Account>(getContext()) {
            @Override
            public void onSuccess(Account data) {
                if (TextUtils.isEmpty(data.wallet_password)) {
                    AlertDialog alertDialog2 = new AlertDialog.Builder(getContext())
                            .setTitle("")
                            .setMessage("请设置6位支付密码")
                            .setIcon(R.mipmap.ic_launcher)
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加"Yes"按钮
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    dialogInterface.dismiss();
                                    startActivity(new Intent(getContext(), PassActivity.class));
                                }
                            })

                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加取消
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    dialogInterface.dismiss();
                                }
                            })
                            .create();
                    alertDialog2.show();
                } else {

                    if (keyong_check.isChecked()) {

                        requestRuntimePermisssions(PAY_PERMISSION, new PermissionListener() {
                            @Override
                            public void onGranted() {//同意
                                oilPassDialog = new OilPassDialog(getContext());
                                oilPassDialog.setonclick(new OilPassDialog.Onclick() {
                                    @Override
                                    public void Yes(String pass) {
                                        if (getIntent().getStringExtra("orderId") == null) {
                                            if (wx_check.isChecked()) {
                                                orderpay("3", pass);
                                            }
                                            if (ali_check.isChecked()) {
                                                orderpay("2", pass);
                                            }
                                            if (keyong_check.isChecked()) {
                                                orderpay("1", pass);
                                            }
                                        } else {
                                            if (wx_check.isChecked()) {
                                                orderIdPay("3", orderId, pass);
                                            }
                                            if (ali_check.isChecked()) {
                                                orderIdPay("2", orderId, pass);
                                            }
                                            if (keyong_check.isChecked()) {
                                                orderIdPay("1",orderId, pass);
                                            }
                                        }
                                    }
                                });

                                oilPassDialog.show();
                            }

                            @Override
                            public void onDenied(List<String> deniedList) {
                            }
                        });


                    } else {

                        requestRuntimePermisssions(PAY_PERMISSION, new PermissionListener() {
                            @Override
                            public void onGranted() {//同意
                                if (getIntent().getStringExtra("orderId") == null) {
                                    if (wx_check.isChecked()) {
                                        orderpay("3", "");
                                    }
                                    if (ali_check.isChecked()) {
                                        orderpay("2", "");
                                    }
                                    if (keyong_check.isChecked()) {
                                        orderpay("1", "");
                                    }
                                } else {
                                    if (wx_check.isChecked()) {
                                        orderIdPay("3", orderId, "");
                                    }
                                    if (ali_check.isChecked()) {
                                        orderIdPay("2", orderId, "");
                                    }
                                    if (keyong_check.isChecked()) {
                                        orderIdPay("1",orderId, "");
                                    }
                                }
                            }

                            @Override
                            public void onDenied(List<String> deniedList) {
                            }
                        });
                    }

                }
            }
        });
    }


    private void orderpay(String payment, String pass) {
        //1钱包2支付宝2微信
        Map<String, String> map = new HashMap<>();
        map.put("addressId", aid);
        map.put("orders_total", price);
        map.put("jian", "0");
        map.put("cartIds", cardid);
        map.put("leave_word", desc);
        map.put("pay_method", payment);
        map.put("recordId", couponId);
        map.put("wallet_password", pass);
        map.put("pei_date",pei_date );
        map.put("pei_time", pei_time);
        apiDataRepository.confrimOrder(map, new ApiNetResponse<PayBean>(getContext()) {
            @Override
            public void onSuccess(PayBean data) {
                showLoading("");
                if (data.pay_method == 2) {
                    AliPay.createInstance(PayActivity.this, mPayResultListener).pay(data.alipay);
                } else if (data.pay_method == 3) {
                    WxPay.getInstance(PayActivity.this).pay(data.weixin, mPayResultListener);
                } else if (data.pay_method == 1) {
                    showMsg("支付成功");
                    hideLoading();

                    Intent intent = new Intent(getContext(), OrdersActivity.class);
                    intent.putExtra("position", 2);
                    startActivity(intent);

                    finish();
                }
            }
        });
    }

    private void orderIdPay(String payment, String id, String pass) {
        //1钱包2支付宝2微信
        Map<String, String> map = new HashMap<>();
        map.put("pay_method", payment);
        map.put("orderId", id);
        map.put("wallet_password", pass);
        apiDataRepository.orderIdPay(map, new ApiNetResponse<PayBean>() {
            @Override
            public void onSuccess(PayBean data) {
                showLoading("");
                if (data.pay_method == 2) {
                    AliPay.createInstance(PayActivity.this, mPayResultListener).pay(data.alipay);
                } else if (data.pay_method == 3) {
                    WxPay.getInstance(PayActivity.this).pay(data.weixin, mPayResultListener);
                } else if (data.pay_method == 1) {
                    showMsg("支付成功");
                    hideLoading();

                    Intent intent = new Intent(getContext(), OrdersActivity.class);
                    intent.putExtra("position", 2);
                    startActivity(intent);

                    finish();
                }
            }
        });
    }

    PayResultListener mPayResultListener = new PayResultListener() {
        @Override
        public void onSuccess(String info) {
            //后台确认支付结果
            showMsg("支付成功");
            hideLoading();

            Intent intent = new Intent(getContext(), OrdersActivity.class);
            intent.putExtra("position", 2);
            startActivity(intent);

            finish();
        }

        @Override
        public void onFail(String info) {
            hideLoading();

            finish();
            if (info != null && (info.equals("{6001}")||info.equals("用户取消"))) {
                showMsg("取消支付");

                Intent intent = new Intent(getContext(), OrdersActivity.class);
                intent.putExtra("position", 1);
                startActivity(intent);
                return;
            }


            Intent intent = new Intent(getContext(), OrdersActivity.class);
            intent.putExtra("position", 2);
            startActivity(intent);
            showMsg(info);

        }
    };

}
